// admin 管理员登录接口
const express=require('express')
const router=express.Router()
const Response=require('../utils/Response')
//引入连接池
const pool=require('../utils/db')
let jwt = require('jsonwebtoken')
const JWT_SECRET_KEY = 'user'
let expiresIn = '3h'

/**
 * 管理员登录业务
 */
router.post('/admin/login',(req,res)=>{
    let {username , password}=req.body
    console.log('admin:',req.body);
    let sql="select * from cyss_administrator where admin_name=? and admin_pwd=?"
    pool.query(sql,[username,password],(error,result)=>{
        if(error){
            res.send(Response.error(500,error))
            throw error
        }
        if(result.length==0){
            res.send(Response.error(400,'账号密码输入错误'))
        }else{
            // 登录的用户对象
            // console.log('result[0]:',admin);
            // let admin = result[0]
            //  admin_id: 1,admin_pwd: '123456',
//   admin_phone: '18841442432', admin_name: 'admin'
            let user = {pwd:result[0].admin_pwd,name:result[0].admin_name}
            
            let token = jwt.sign(user,JWT_SECRET_KEY,{ expiresIn })
            console.log(token);
            // 设置暴露响应头内容
            res.set('Access-Control-Expose-Headers','token')
            res.set('token',token)
            res.send(Response.ok({user,token}))
        }
    })
})

module.exports=router